package com.yuexun.dhdoctor.module.meeting.ui;

import android.Manifest;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.BaseKJActivity;
import com.yuexun.dhdoctor.module.meeting.zxing.MeetingCheckActivityHandler;
import com.yuexun.dhdoctor.module.meetingMaterial.Act_MeetingMaterialDetail;
import com.yuexun.dhdoctor.module.meetingNew.ui.Act_MeetingNew_Detail;
import com.yuexun.dhdoctor.zxing.camera.CameraManager;
import com.yuexun.dhdoctor.zxing.decodeing.InactivityTimer;
import com.yuexun.dhdoctor.zxing.view.ViewfinderView;


import org.kymjs.kjframe.ui.ViewInject;

import java.io.IOException;
import java.util.List;
import java.util.Vector;

import butterknife.Bind;
import butterknife.ButterKnife;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;


public class Act_MeetingCheck extends BaseKJActivity implements Callback, EasyPermissions.PermissionCallbacks {

    @Bind(R.id.preview_view)
    SurfaceView surfaceView;
    @Bind(R.id.viewfinder_view)
    ViewfinderView viewfinderView;

    //权限参数
    private String[] params = {Manifest.permission.CAMERA};

    private MeetingCheckActivityHandler handler;
    private boolean hasSurface;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private static final float BEEP_VOLUME = 0.10f;
    private boolean vibrate;
    //	private Button rightB;
    private boolean light;

    private int type;

    //1：传送服务
    private int TAG;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.camera);
        ButterKnife.bind(this);
        CameraManager.init(getApplication());
        //ViewUtil.addTopView(getApplicationContext(), this, R.string.scan_card);
        type = getIntent().getExtras().getInt("type", 1);
        TAG = getIntent().getExtras().getInt("TAG", 0);
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
        checkPermission();
    }

    @Override
    protected void onResume() {
        super.onResume();
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;

        playBeep = true;
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        initBeepSound();
        vibrate = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        CameraManager.get().closeDriver();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    /**
     * Handler scan result
     *
     * @param result
     * @param barcode
     */
    public void handleDecode(Result result, Bitmap barcode) {
        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();
        String resultString = result.getText();
        if (resultString.equals("")) {
            Toast.makeText(Act_MeetingCheck.this, "Scan failed!", Toast.LENGTH_SHORT).show();
        } else {
            if (resultString.contains("?")) {
                resultString = resultString.split("\\?")[1];
            }

            if (TAG == 0) {                   //会议详情、会议材料、学习考勤、设备信息
                if (resultString.split(":")[0].equals("meetingId")) {                 //会议详情
                    if (type == 0) {           //签到回调
                        Intent resultIntent = new Intent();
                        Bundle bundle = new Bundle();
                        bundle.putString("resultString", resultString);
                        resultIntent.putExtras(bundle);
                        this.setResult(RESULT_OK, resultIntent);
                        finish();
                    } else if (type == 1) {     //直接进入
                        Intent resultIntent;
                        resultIntent = new Intent(this, Act_MeetingNew_Detail.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("meetingId", resultString.split(":", 2)[1].split(",")[0]);
                        bundle.putString("resultString", resultString);
                        bundle.putInt("type", 1);
                        resultIntent.putExtras(bundle);
                        startActivity(resultIntent);
                        finish();
                    }
                } else if (resultString.split(":")[0].equals("meetingMaterialId")) {   //会议材料
                    Intent intent = new Intent(this, Act_MeetingMaterialDetail.class);
                    intent.putExtra("meetingMaterialId", resultString.split(":")[1]);
                    startActivity(intent);
                    finish();
                }else {
                    ViewInject.toast(resultString);
                    continuePreview();
                }
            }

        }
//		Act_MeetingCheck.this.finish();
    }

    //重新识别
    private void continuePreview() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (handler != null) {
                    handler.restartPreviewAndDecode();
                }
            }
        }, 3000);
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            Log.e("jx", ioe.getMessage().toString());
            return;
        } catch (RuntimeException e) {
            Log.e("jx", e.getMessage().toString());
            return;
        }
        if (handler == null) {
            handler = new MeetingCheckActivityHandler(this, decodeFormats, characterSet);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;

    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();

    }

    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it
            // too loud,
            // so we now play on the music stream.
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(
                    R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final OnCompletionListener beepListener = new OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };

//	private void flashlight() {
//		if(!light) {
//			CameraManager.get().openLight();
//
//			light = true;
//			rightB.setText("关灯");
//		} else {
//			CameraManager.get().closeLight();
//
//			light = false;
//			rightB.setText("开灯");
//		}
//	}

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.back:
                finish();
                break;
//			case R.id.ib_right:
//				flashlight();
//				break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 检查获取权限
     */
    private void checkPermission() {
        if (EasyPermissions.hasPermissions(this, params)) {
            // Already have permission, do the thing
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, getString(R.string.easypermission_camera), 100, params);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        onResume();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            //这个方法有个前提是，用户点击了“不再询问”后，才判断权限没有被获取到
            new AppSettingsDialog.Builder(this)
                    .setRationale(getString(R.string.easypermission_open_set))
                    .setTitle("必需权限")
                    .build()
                    .show();
        } else if (!EasyPermissions.hasPermissions(this, params)) {
            //这里响应的是除了AppSettingsDialog这个弹出框，剩下的两个弹出框被拒绝或者取消的效果
            finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            if (!EasyPermissions.hasPermissions(this, params)) {
                //这里响应的是AppSettingsDialog点击取消按钮的效果
                finish();
            }
        }
    }

}
